import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress'
import 'nprogress/nprogress.css'
import { getToken } from '@/utils/auth'
import { isRelogin } from '@/utils/request'
import getPageTitle from '@/utils/get-page-title'
import Layout from '@/layout'

NProgress.configure({ showSpinner: false })

const whiteList = ['/login', '/register']

router.beforeEach((to, from, next) => {
  NProgress.start()
  // 获取page标题
  document.title = getPageTitle(to.meta.title)

  const hasToken = getToken()
  if (hasToken) {
    to.meta.title && store.dispatch('settings/setTitle', to.meta.title)
    // 如果已登录，重定向到主页
    if (to.path === '/login') {
      next({ path: '/' })
      NProgress.done()
    } else {
      const hasLogin = store.getters.name && store.getters.name.length > 0
      if (hasLogin) {
        next()
      } else {
        if (store.getters.name) {
          next()
        } else {
          // 取用户登录信息
          store.dispatch('GetInfo').then(() => {
            store.dispatch('ListRouters').then(routers => {
              // hack方法 确保addRoutes已完成
              next({ ...to, replace: true })
            })
          }).catch(err => {
            store.dispatch('LogOut').then(() => {
              Message.error(err)
              next({ path: '/' })
              NProgress.done()
            })
          })
        }
      }
    }
  } else {
    // 没有token
    if (whiteList.indexOf(to.path) !== -1) {
      // 在免登录白名单，直接进入
      next()
    } else {
      next(`/login?redirect=${to.fullPath}`) // 否则全部重定向到登录页
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  NProgress.done()
})
